package com.gzck.gzck_verson2.utils;

import com.gzck.gzck_verson2.configuration.MinioAutoConfiguration;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传
 */
@Service
public class MinioService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioAutoConfiguration minioAutoConfiguration;

    public String uploadFile(InputStream inputStream, String objectName, String originalFileName) {
        try {
            String bucketName = minioAutoConfiguration.getBucketName();

            // 生成带有时间戳的新文件名
            String newFileName = generateNewFileName(originalFileName);

            String objectPath = objectName + "/" + newFileName;

            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectPath)
                    .stream(inputStream, inputStream.available(), -1)
                    .build());

            // 直接拼接访问地址
            return minioAutoConfiguration.getEndpoint() + "/" + bucketName + "/" + objectPath;
        } catch (Exception e) {
            // 处理异常
            e.printStackTrace();
            return null;
        }
    }

    // 生成带有时间戳的新文件名
    private String generateNewFileName(String originalFileName) {
        // 获取当前时间戳
        long currentTimeStamp = System.currentTimeMillis();

        // 从文件名中提取文件扩展名（如果有的话）
        String fileExtension = "";
        String firstExtension = "";
        int lastDotIndex = originalFileName.lastIndexOf(".");
        if (lastDotIndex != -1) {
            fileExtension = originalFileName.substring(lastDotIndex);
            firstExtension = originalFileName.substring(0,lastDotIndex);
        }

        // 构建新的文件名
        return firstExtension + "_" + currentTimeStamp + fileExtension;
    }

}
